#include "mainscene.h"
#include"config.h"
#include<QIcon>
#include<QPainter>
#include<QMouseEvent>
MainScene::MainScene(QWidget *parent)
    : QWidget(parent)
{//初始化场景
    initScene();
    //start
   playGame();
}
MainScene::~MainScene()
{
}

void MainScene::initScene()
{//设置窗口尺寸及标题图标
    setFixedSize(GAME_WIDTH, GAME_HEIGHT);
    setWindowTitle(GAME_TITLE);
    //加载图标
    setWindowIcon(QIcon(GAME_ICON));
    //定时器设置
    m_Timer.setInterval(GAME_RATE);
}

void MainScene::playGame(){
    m_Timer.start();//游戏开始
    connect(&m_Timer , &QTimer::timeout,[=](){
        updatePosition();
        update();
      });
}
void MainScene::updatePosition()
{//更新地图
    m_map.mapPosition();
    //更新子弹
    m_hero.shoot();
    for(int i = 0; i < BULLET_NUM;i++)
    {
        if(m_hero.m_bullets[i].m_Free == false)
        {
            m_hero.m_bullets[i].updatePosition();
        }

    }

}
void MainScene::paintEvent(QPaintEvent*)
{
    QPainter painter(this);
   //绘制地图
    painter.drawPixmap(0,m_map.m_map1_posY,m_map.m_map1);
    painter.drawPixmap(0,m_map.m_map2_posY,m_map.m_map2);
    //绘制飞机
    painter.drawPixmap(m_hero.m_X,m_hero.m_Y,m_hero.m_Plane);
   //绘制子弹
    for(int i=0;i < BULLET_NUM;i++)
    {    if(m_hero.m_bullets[i].m_Free == false)
         painter.drawPixmap(m_hero.m_bullets[i].m_X,m_hero.m_bullets[i].m_Y,m_hero.m_bullets[i].m_Bullet);

    }
}

void MainScene::mouseMoveEvent(QMouseEvent * event)
{
    int x = event->x() - m_hero.m_Rect.width()*0.5;
    int y = event->y() - m_hero.m_Rect.height()*0.5;
       if(x <=0 )
       {
           x = 0;
       }
       if(x >= GAME_WIDTH - m_hero.m_Rect.width())
       {
           x = GAME_WIDTH - m_hero.m_Rect.width();
       }
       if(y <= 0)
       {
           y=0;
       }
       if(y >= GAME_HEIGHT- m_hero.m_Rect.height())
       {
           y = GAME_HEIGHT- m_hero.m_Rect.height();
       }
    m_hero.setPosition(x,y);
}
